package com.yao.auth.config;

import com.yao.auth.filter.CustomerCorsFilter;
import com.yao.auth.handler.MyAccessDenyHandler;
import com.yao.auth.handler.MyAuthenticationEntryPoint;
import com.yao.auth.service.impl.CustomRemoteTokenServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/2 14:20
 * FileName: ResourceServerConfig
 * Description:
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    ResourceServerProperties resourceServerProperties;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        super.configure(resources);
//        resources.resourceId("demo");

        resources.resourceId(resourceServerProperties.getResourceId());
        resources.tokenServices(customRemoteTokenService);

        resources.authenticationEntryPoint(myAuthenticationEntryPoint)
                .accessDeniedHandler(myAccessDenyHandler);

    }

    @Autowired
    MyAccessDenyHandler myAccessDenyHandler;

    @Autowired
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.addFilterBefore(customerCorsFilter, WebAsyncManagerIntegrationFilter.class);
    }

    @Autowired
    CustomerCorsFilter customerCorsFilter;
    @Qualifier("customRemoteTokenService")
    @Autowired
    RemoteTokenServices customRemoteTokenService;

    @Bean
    @Primary
    RemoteTokenServices customRemoteTokenService(){
        CustomRemoteTokenServiceImpl services=new CustomRemoteTokenServiceImpl();
        services.setCheckTokenEndpointUrl(this.resourceServerProperties.getTokenInfoUri());
        services.setClientId(this.resourceServerProperties.getClientId());
        services.setClientSecret(this.resourceServerProperties.getClientSecret());
        return services;
    }
}
